import { getKeyMap } from '../helpers/keycodes'
import { assignKeyHandler } from '../helpers/helper'

function bindEvent(el, { value, modifiers }, alias) {
  el._keyMap = getKeyMap(value, alias)
  el._keyHandler = e => assignKeyHandler(e, el._keyMap, modifiers)

  document.addEventListener('keydown', el._keyHandler)
  document.addEventListener('keyup', el._keyHandler)
}

function unbindEvent(el) {
  document.removeEventListener('keydown', el._keyHandler)
  document.removeEventListener('keyup', el._keyHandler)
}

export function buildDirective(alias) {
  return {
    mounted(el, binding) {
      bindEvent(el, binding, alias)
    },
    updated(el, binding) {
      if (binding.value !== binding.oldValue) {
        unbindEvent(el)
        bindEvent(el, binding, alias)
      }
    },
    unmounted(el) {
      unbindEvent(el)
    },
  }
}